package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import io.netty.util.concurrent.SingleThreadEventExecutor;
import org.apache.ibatis.javassist.bytecode.analysis.Executor;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.api.stream.StreamReadParams;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * ReabbitMQ 版本
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;
    @Resource
    private IVoucherOrderService iVoucherOrderService;
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRRPT;

    static {
        SECKILL_SCRRPT = new DefaultRedisScript<>();
        SECKILL_SCRRPT.setLocation(new ClassPathResource("Seckill.lua"));
        SECKILL_SCRRPT.setResultType(Long.class);
    }

    /**
     * 抢购秒杀券
     * @param voucherId
     */
    public Result seckillVoucher(Long voucherId) {
        long orderId = redisIdWorker.nextId("order");
        Long userId = UserHolder.getUser().getId();
        // 是否有下单资格
        // 执行lua脚本
        Long res = stringRedisTemplate.execute(
                SECKILL_SCRRPT,
                Collections.emptyList(),
                String.valueOf(voucherId), String.valueOf(userId),String.valueOf(orderId)
        );

        if(res!=0){
            // 不为0说明下单失败
            return Result.fail(res == 1 ? "库存不足":"用户已经下过一单了");
        }
        // 有下单资格，已存入消息队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(voucherId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        // 发送消息到消息队列

        try {
            rabbitTemplate.convertAndSend("order.direct","order.success",voucherOrder);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Result.ok(orderId);
    }


    /**
     * 更新数据库
     * @param voucherOrder
     */
    // 创建单线程线程池
    ExecutorService SECKILL_ORDER_EXECUTOR =  Executors.newSingleThreadExecutor();


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("order.queue"),
            exchange = @Exchange("order.direct"),
            key = "order.success"
    ))
    public void orderQueueListener(VoucherOrder voucherOrder) {
        SECKILL_ORDER_EXECUTOR.execute(()->{
            createOrder(voucherOrder);
        });
    }

    @Transactional
    public void createOrder(VoucherOrder voucherOrder) {
        // 扣除库存
        boolean success = iSeckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id",voucherOrder.getVoucherId())
                .gt("stock",0)
                .update();
        if(!success){
            log.error("库存不足");
        }
        // 添加订单信息
        iVoucherOrderService.save(voucherOrder);
    }
}
